import axios from "axios";
import router from "../router";

const instance = axios.create({
  baseURL: import.meta.env.VITE_API_PREFIX,
  timeout: 1000 * 30,
});

//请求拦截器
instance.interceptors.request.use(
  function (config) {
    //token
    let token = localStorage.getItem("token");
    if (token) {
      config.headers.token = token;
    }

    return config;
  },
  function (error) {
    showToast(error.message);
    return Promise.reject(error);
  }
);

//响应拦截器
instance.interceptors.response.use(
  function (response) {
    const data = response.data;
    if (data && data.code == 2) {
      showToast(data.message);
      logout();
      return Promise.reject(data);
    }

    return data;
  },
  function (error) {
    showToast(error.message);
    return Promise.reject(error);
  }
);

/**
 * 退出登录
 */
const logout = () => {
  localStorage.removeItem("token");
  router.replace("/login");
};

export default instance;
